#include "Timer.h"
#include "System\F2806x_Device.h"

// 80Mhz SYSCLKOUT (80Mhz/1)
#define TICKSPERSEC 80000000L

void Timer::Init()
{
	CpuTimer0Regs.PRD.all = 0xFFFFFFFF; // free running timer at 80Mhz
    CpuTimer0Regs.TPR.all  = 0; // Set pre-scale counter to divide by 1 (SYSCLKOUT):
    CpuTimer0Regs.TPRH.all  = 0;

    // Initialize timer control register:
    CpuTimer0Regs.TCR.bit.TSS = 1;      // 1 = Stop timer, 0 = Start/Restart Timer
    CpuTimer0Regs.TCR.bit.TRB = 1;      // 1 = reload timer
    CpuTimer0Regs.TCR.bit.TIE = 0;      // 0 = Disable/ 1 = Enable Timer Interrupt
	CpuTimer0Regs.TCR.all = 0x0000; // start timer
	
	m_StartTime = 0;
}

void Timer::BeginPeriod()
{
	m_StartTime = CpuTimer0Regs.TIM.all;
}

bool Timer::HasElapsed(float time)
{
	Uint32 totalTimeTicks = time*TICKSPERSEC;	
	Uint32 currentTimeStamp = CpuTimer0Regs.TIM.all;
	Uint32 deltaTime = m_StartTime-currentTimeStamp; // down counter!	

	if( deltaTime < totalTimeTicks ) return false;
	return true;
}

void Timer::WaitPeriod(float time)
{
	BeginPeriod();
	while( !HasElapsed(time) );
}

float Timer::ElapsedTime()
{
	Uint32 currentTimeStamp = CpuTimer0Regs.TIM.all;
	Uint32 deltaTime = m_StartTime-currentTimeStamp;	

	float elapsed = (float)deltaTime/(float)TICKSPERSEC;
	
	return elapsed;
}
